import json
import struct

import numpy as np


def to_redis_json(rds, value, key):
    return rds.set(key, json.dumps(value))


def from_redis_json(rds, key):
    val = rds.get(key)
    return list() if val is None else json.loads(rds.get(key))


def to_redis_numpy(rds, value, key):
    h, w, z = value.shape
    shape = struct.pack('>III', h, w, z)
    encoded = shape + value.tobytes()
    return rds.set(key, encoded)


def from_redis_numpy(rds, key):
    encoded = rds.get(key)
    if encoded is None:
        return None
    h, w, z = struct.unpack('>III', encoded[:12])
    return np.frombuffer(encoded, dtype=np.float32, offset=12).reshape(h, w, z)
